<?php

namespace Module\Model;

use Zend\Db\TableGateway\TableGateway;

class ModuleTable {

    protected $tableGateway;

    public function getTableGateway() {
        return $this->tableGateway;
    }

    public function setTableGateway($tableGateway) {
        $this->tableGateway = $tableGateway;
    }

    public function __construct(TableGateway $tableGateway) {
        $this->tableGateway = $tableGateway;
    }

    public function isExist($module_name) {
        $result = $this->tableGateway->select(array('key_name' => $module_name));
        if ($result->count()) {
            return true;
        } else {
            return false;
        }
    }

    public function fetchAll() {
        $sel = new \Zend\Db\Sql\Select();
        $sel->from('modules')->order('module_group_id ASC, name ASC');
        return $this->tableGateway->selectWith($sel);
    }

    public function getGeneralModules() {
        $select = new \Zend\Db\Sql\Select();
        $where = new \Zend\Db\Sql\Where();
        $where->equalTo('module_group_id', 1);

        $select->from('modules')->columns(array('mid'))->where($where);

        return $this->tableGateway->selectWith($select)->toArray();
    }

    public function fetchAllForJson() {
        $select = new \Zend\Db\Sql\Select();
        $select->from('modules')->columns(array('mid', 'key_name', 'name', 'description'))->order('name ASC ');
        return $this->tableGateway->selectWith($select)->toArray();
    }

    public function getGeneralModulesForJson() {
        $select = new \Zend\Db\Sql\Select();
        $where = new \Zend\Db\Sql\Where();
        $where->equalTo('module_group_id', 1);

        $select->from('modules')->columns(array('mid', 'key_name', 'name', 'description'))->where($where)->order('name ASC ');

        return $this->tableGateway->selectWith($select)->toArray();
    }

    public function save($data) {

        $savedData = array(
            'key_name' => $data['key_name'],
            'name' => $data['name'],
            'description' => $data['description'],
            'state' => $data['state'],
            'author' => $data['author'],
            'version' => $data['version'],
            'icon' => $data['icon'],
        );

        $this->tableGateway->insert($savedData);
        return $this->tableGateway->getLastInsertValue();
    }

    public function getById($id) {
        return $this->tableGateway->select(array('mid' => $id))->current();
    }

    public function remove($id) {
        $this->tableGateway->delete(array('mid' => $id));
    }

}

?>